<script lang="ts" setup>
import {navigation, PriMsgRoute, TopicListRoute, UserRoute} from "./router";
import {onMounted, onUnmounted, ref, watch} from "vue";
import {useRoute, useRouter} from "vue-router";
import {useAccountStore} from "./store/AccountStore.ts";
import {useResourceStore} from "./store/ResourceStore.ts";
import type {UserDetail} from "./network/types/User.ts";
import {useUserStore} from "./store/UserStore.ts";
import {useForumStore} from "./store/ForumStore.ts";
import type {FavorForum} from "./network/types/Forum.ts";
import {useNoticeStore} from "./store/NoticeStore.ts";
import type {NoticeBody} from "./network/types/Notice.ts";
import NgaNotice from "./components/notice/NgaNotice.vue";
import {ElMessageBox} from "element-plus";
import {todo, toNumber} from "./utils/Utils.ts";

const router = useRouter();
const defaultActive = ref("/forum/index")
const route = useRoute();
const routers = navigation
const keyFindUser = '找人'

const resourceStore = useResourceStore();
const accountStore = useAccountStore();
const forumStore = useForumStore();
const userStore = useUserStore();
const currentUser = ref<UserDetail>()
const noticeBody = ref<NoticeBody>()
const showNotice = ref<boolean>()
const activeName = ref<string>()
accountStore.loadAccounts()
let interval: number | undefined

const readAll = () => {
  noticeBody.value?.replies?.forEach(i => i.unread = false)
  noticeBody.value?.messages?.forEach(i => i.unread = false)
  noticeBody.value?.likes?.forEach(i => i.unread = false)
}

const clearNotice = () => {
  ElMessageBox.confirm('确定要清空所有消息吗？', '提示', {}).then(async () => {
    await useNoticeStore().clear()
    noticeBody.value = undefined
    showNotice.value = false
  })
}

const handleSelect = async (key: string, keyPath: string[]) => {
  console.debug(key, keyPath)
  const type = keyPath[0];
  if (key === keyFindUser) {
    // 弹窗要求输入准确用户名
    ElMessageBox.prompt('请输入准确用户名或用户ID', '找人', {}).then(async ({value}) => {
      const userId = toNumber(value)
      if (userId) {
        await router.push({name: UserRoute.USER_CENTER_ID, params: {userId}})
      } else {
        await router.push({name: UserRoute.USER_CENTER_USERNAME, params: {username: value}})
      }
    })
    return
  }
  if (type === 'accounts') {
    console.log('切换账号', keyPath[1])
    await router.push({query: Object.assign({...route.query}, {account: key})})
    // 提醒消息
    loadNotice()
    return
  }
  if (type == 'favorForums') {
    const path = keyPath[1]
    const id = path.substring(1)
    console.log('切换收藏版面', path)
    if (path.startsWith('s')) {
      await router.push({name: TopicListRoute.COL_LIST, params: {stid: id}})
    } else {
      await router.push({name: TopicListRoute.FORUM_LIST, params: {fid: id}})
    }
    return
  }
  if (key === "notice") {
    showNotice.value = !showNotice.value
    return
  }
  if (key.startsWith('user-')) {
    const params = {userId: currentUser.value?.userId}
    switch (key) {
      case 'user-center': {
        await router.push({name: UserRoute.USER_CENTER_ID, params})
        return
      }
      case 'user-topic': {
        await router.push({name: TopicListRoute.USER_TOPIC, params})
        return
      }
      case 'user-reply': {
        await router.push({name: TopicListRoute.USER_REPLIES, params})
        return
      }
      case 'user-message': {
        await router.push({name: PriMsgRoute.LIST})
        return
      }
      case 'user-favor': {
        await router.push({name: UserRoute.USER_FAVOR, params})
        return
      }
      case 'user-items': {
        await router.push({name: UserRoute.USER_ITEMS, params})
        return
      }
      default: {
        todo(key)
        return
      }
    }
  }

  defaultActive.value = key
  await router.push(keyPath.join("/"))
}

const favorForumId = (f: FavorForum) => f.stid ? 's' + f.stid : 'f' + f.fid

// 加载主题配色
const loadTheme = async () => {
  const theme = localStorage.getItem("theme") || "green"

  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.type = 'text/css';
  link.href = `/theme/theme-${theme}.css`; // 根据主题加载不同的 CSS 文件
  document.head.appendChild(link);

  await resourceStore.bbsCode()
  await resourceStore.uiResource()
  await resourceStore.thirdPartyEmoteCategory()
}
// 加载当前用户信息
const loadCurrentUser = () => {
  userStore.detailHtml(accountStore.getAccountUserId(), undefined).then(res => {
    currentUser.value = res
  })
};

// 加载与当前用户相关的数据
const loadUserData = () => {
  // 用户信息
  loadCurrentUser();
  // 更新收藏版面
  forumStore.favorList()
  // 加载屏蔽配置
  userStore.blockConfigGet()
}

const loadNotice = () => {
  useNoticeStore().list().then(res => noticeBody.value = res)
}

const unreadCount = (noticeBody: NoticeBody | undefined) => {
  const c1 = noticeBody?.replies?.filter(i => i.unread)?.length || 0
  const c2 = noticeBody?.likes?.filter(i => i.unread)?.length || 0
  const c3 = noticeBody?.messages?.filter(i => i.unread)?.length || 0
  return c1 + c2 + c3
}

onMounted(() => {
  loadTheme()
  // 提醒消息
  loadNotice()
  // 周期性更新提醒消息
  interval = setInterval(() => loadNotice(), 30 * 1000)
})

onUnmounted(() => {
  clearInterval(interval)
})

watch(route, () => {
  //切换路由时关闭提醒消息抽屉
  showNotice.value = false

  loadUserData()
})

router.beforeEach((to, from, next) => {
  // 复制 account 参数
  // console.log(to, from)
  if (from.query.account && !to.query.account) {
    to.query.account = from.query.account
    next(to)
  } else {
    next()
  }
})


</script>

<template>
  <!--顶部菜单栏，导航按钮-->
  <div class="bg-color" style="padding: 4px">
    <!--固定导航按钮-->
    <el-menu
        :default-active="defaultActive"
        active-text-color="#ffd04b"
        background-color="#545c64"
        mode="horizontal"
        text-color="#fff"
        @select="handleSelect"
    >
      <template v-for="route in routers">
        <el-sub-menu v-if="route.children" :index="route.path">
          <template #title>
            {{ route.name }}
          </template>
          <template #default>
            <el-menu-item v-for="child in route.children" :key="route.path+'/'+child.path" :index="child.path">
              {{ child.name }}
            </el-menu-item>
          </template>
        </el-sub-menu>
        <el-menu-item v-else :key="route.path" :index="route.path">
          {{ route.name }}
        </el-menu-item>
      </template>
      <!--找人-->
      <el-menu-item :index="keyFindUser">
        找人
      </el-menu-item>
      <!--账号切换-->
      <el-sub-menu index="accounts">
        <template #title>
          <!--  当前账号头像， 用户名-->
          <el-avatar v-if="currentUser?.avatars?.[0]" :src="currentUser?.avatars?.[0]"/>
          <span v-if="currentUser">{{ currentUser.username }}</span>
        </template>
        <!--   剩余账号用户名 ，点击切换-->
        <el-menu-item v-for="acc in accountStore.accounts.filter(i=>i.userId!==currentUser?.userId)" :key="acc.userId" :index="acc.userId.toString()">
          {{ acc.username }}
        </el-menu-item>
      </el-sub-menu>
      <!--收藏版面切换-->
      <el-sub-menu index="favorForums">
        <template #title>收藏版面</template>
        <el-menu-item v-for="favor in forumStore.favorForums" :key="favorForumId(favor)" :index="favorForumId(favor)">
          {{ favor.name }}
        </el-menu-item>
      </el-sub-menu>
      <!--提醒消息按钮-->
      <el-menu-item key="notice" index="notice">
        <el-badge :offset="[0,10]" :show-zero="false" :type="unreadCount(noticeBody)?'danger':'success'" :value="unreadCount(noticeBody)">
          提醒消息
        </el-badge>
      </el-menu-item>
      <!--用户相关导航-->
      <el-sub-menu index="user">
        <template #title>我的</template>
        <el-menu-item index="user-center">用户中心</el-menu-item>
        <el-menu-item index="user-topic">我的主题</el-menu-item>
        <el-menu-item index="user-reply">我的回复</el-menu-item>
        <el-menu-item index="user-favor">我的收藏</el-menu-item>
        <el-menu-item index="user-message">我的私信</el-menu-item>
        <el-menu-item index="user-items">我的道具</el-menu-item>
      </el-sub-menu>
    </el-menu>
  </div>
  <!--主体部分-->
  <div class="bg-color text-color-normal" style="padding: 4px;min-height: 100%">
    <!--路由插槽-->
    <RouterView/>
    <!--回到顶部按钮-->
    <el-backtop :bottom="100" :right="100"/>
    <!--提醒消息抽屉-->
    <el-drawer v-model="showNotice" :with-header="false" size="70%">
      <template #default>
        <el-tabs v-if="showNotice" v-model="activeName">
          <el-tab-pane>
            <template #label>
              <el-badge :show-zero="false" :value="noticeBody?.replies?.filter(i=>i.unread)?.length ||0">
                回复
              </el-badge>
            </template>
            <div style="text-align: start">
              <ol>
                <li v-for="it in noticeBody?.replies">
                  <nga-notice :notice="it"/>
                </li>
              </ol>
            </div>
          </el-tab-pane>
          <el-tab-pane>
            <template #label>
              <el-badge :show-zero="false" :value="noticeBody?.messages?.filter(i=>i.unread)?.length ||0">
                私信
              </el-badge>
            </template>
            <div style="text-align: start">
              <ol>
                <li v-for="it in noticeBody?.messages">
                  <nga-notice :notice="it"/>
                </li>
              </ol>
            </div>
          </el-tab-pane>
          <el-tab-pane>
            <template #label>
              <el-badge :show-zero="false" :value="noticeBody?.likes?.filter(i=>i.unread)?.length ||0">
                点赞
              </el-badge>
            </template>
            <div style="text-align: start">
              <ol>
                <li v-for="it in noticeBody?.likes">
                  <nga-notice :notice="it"/>
                </li>
              </ol>
            </div>
          </el-tab-pane>
        </el-tabs>
      </template>
      <template #footer>
        <div style="text-align: start">
          <el-button type="danger" @click="clearNotice">清空消息</el-button>
          <el-button type="warning" @click="readAll">全部已读</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style scoped>
.account-avatar {
  border-radius: 50%;
  width: 60px; /* 可选，设置宽度 */
  height: 60px; /* 可选，设置高度 */
}

.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}

.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}

.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
</style>
